/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/18 10:24
 */
package org.mechanic.fund.service.product.impl;

import org.mechanic.core.Constants;
import org.mechanic.fund.domain.product.Product;
import org.mechanic.fund.domain.product.ProductStyle;
import org.mechanic.fund.domain.utils.mapper.DtoBeanMapper;
import org.mechanic.fund.repository.product.ProductRepository;
import org.mechanic.fund.service.product.IProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 产品信息服务实现
 *
 * @author mechanic
 * @version 0.0.1
 */
@Service
public class ProductService implements IProductService {
    private static Logger logger = LoggerFactory.getLogger(ProductTypeService.class);

    private ProductRepository productRepository;

    @Autowired
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    /**
     * 返回模糊匹配产品名称、产品代码和完全匹配产品风格类型的产品信息列表
     * @param name 名称
     * @param code 产品代码
     * @param styleId 产品风格类型主键编号
     * @return 产品信息列表
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public List<Product> getProductList(String name, String code, String styleId) {

        ProductStyle style = new ProductStyle();
        style.setId(styleId);
        return (List<Product>)productRepository.findProductListOrderByCreateTimeAsc(
          name,
          code,
          style
        );
    }

    /**
     * 返回匹配指定主键编号的对象
     *
     * @param id 主键编号
     * @return 对象实体
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public Product getById(String id) {
        return this.productRepository.findOne(id);
    }

    /**
     * 保存。 主键为空则create，不为空则update。
     *
     * @param products 被保存的对象集合
     */
    @Override
    public void save(List<Product> products, String operationUserId) {
        this.productRepository.save(DtoBeanMapper.setOperationToList(products, operationUserId));
    }

    /**
     * 删除匹配主键ID的对象
     *
     * @param id 主键ID
     */
    @Override
    public void delete(String id) {
        try {
            this.productRepository.delete(id);
        } catch (EmptyResultDataAccessException e) {
            logger.info(id + "不存在");
        }
    }
}
